# added by yinchao, Thu July 25 09:57	2024

import socket
import struct

host = "192.168.50.14"
port = 2800

def connect2ff(host, port):
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        soc.connect((host, port))
        print(f"成功连接到服务器 {host}:{port}")

        # 持久连接，等待用户输入并发送给服务器
        while True:
            message = input("请输入发送给服务器的消息（输入 'exit' 断开连接）：")
            if message.lower() == 'exit':
                print("断开连接...")
                break

            # 编码消息并计算长度
            encoded_message = message.encode()
            length = len(encoded_message)

            # 使用两个字节大端编码表示长度
            packed_length = struct.pack('!H', length)
            
            # 发送长度和消息
            soc.sendall(packed_length + encoded_message)
            
            # 接收消息长度（两个字节大端编码）
            length_data = soc.recv(2)
            if not length_data:
                print("服务器断开连接")
                break
            (msg_length,) = struct.unpack('!H', length_data)

            # 接收消息数据
            data = soc.recv(msg_length)
            if not data:
                print("服务器断开连接")
                break
            
            print(f"接收到服务器的回复：{data.decode()}")
    except Exception as e:
        print(f"连接过程中出现错误：{e}")
    
    finally:
        soc.close()
        print("连接已关闭")

connect2ff(host=host, port=port)
